import './index.scss';

import React from 'react';
import { Link, hashHistory } from 'react-router';
import { sliceStringAccordingToByte } from 'utilsPath/string-function.js';
import { ClickImage } from 'componentPath/imgs.jsx';
import { ajax } from 'utilsPath/fetch.js';
import focusImg from 'imgPath/focus.png';
import focusNoImg from 'imgPath/focus-no.png';
import resultsListTitle from 'imgPath/results-list-title.png';

class Results extends React.Component {
    constructor (props) {
        super(props);
        this.state = {
            uid: 0,
            isLogin: false,
            stage: 3,
            endTime: false,
            list: [],
            topThreeData: [],
            listData: [],
            isShowToast: false,
            toastText: '请求错误',
        };
        this.timer = null;
    };

    topThreeTemplate (list) {
        try{
            return list.map((item, index, array) => {
                return (
                    <div className={`top-three${index + 1}`} key={index}>
                        <ClickImage 
                            className="head-img"
                            src={item.avatar}
                            callback={this.redirect.bind(this)}
                            callbackData={['user', item.uid]}/>
                        <p className="name">{sliceStringAccordingToByte(item.screenName, 12)}</p>
                        <p className="combat-num">{item.score}</p>
                        <p className="combat-title">装备值</p>
                        <img src={item.isFollowed?focusNoImg :focusImg} className="watch"
                            onClick={() => this.clickWatch(item, index, array)}/>
                    </div>
                )
            })
        }catch (e) {
            return '';
        };
    };

    listItemTemplate (list) {
        try{
            return list.map((item, index, array) => {
                return (
                    <li className="list-item" key={index}>
                        <p className="index">{item.rank}</p>
                        <ClickImage 
                            className="head-img"
                            src={item.avatar}
                            callback={this.redirect.bind(this)}
                            callbackData={['user', item.uid]}/>
                        <div className="intro">
                            <p className="name">{sliceStringAccordingToByte(item.screenName, 12)}</p>
                            <p className="combat-num">{`装备值：${item.score}`}</p>
                        </div>
                        <img src={item.isFollowed?focusNoImg :focusImg} className="watch"
                            onClick={() => this.clickWatch(item, index, array)}/>
                    </li>
                )
            })
        }catch (e) {
            return '';
        };
    };

    componentWillMount() {
        this.getContentData();
        this.timeSave(10);
    };

    componentWillUnmount() {
        clearTimeout(this.timer);
    };

    render () {
        return (
            <div className={`results-page`}>
                <div className="back-header"></div>
                <div className="back-title">
                    <div className="list-title">
                        {
                            this.topThreeTemplate(this.state.topThreeData)
                        }
                        <img src={resultsListTitle} className="title-img"/>
                    </div>
                </div>
                <div className="back-repeat">
                    <ul className="list-content">
                        {
                            this.listItemTemplate(this.state.listData)
                        }
                    </ul>
                </div>
                <div className="back-bottom">
                    <div className="list-bottom"></div>
                </div>
                {
                    this.state.isShowToast
                        ?<div className="page-toast">{this.state.toastText}</div>
                        :''
                }
            </div>
        );
    };

    getContentData () {
        ajax({
            method: 'get',
            url: '/equipment2018/index_data',
        }).then(res => {
            console.log(res);
            if (res.code != 0) {
                this.showToast(res.msg);
                return;
            };

            let topThreeData = [];
            let listData = [];
            for (let i=0;i<res.list.length;i++) {
                if (i == 1) {
                    topThreeData.unshift(res.list[i]);
                };
                if (i == 2 || i == 0) {
                    topThreeData.push(res.list[i]);
                };
                if ( i>2 ){
                    listData.push(res.list[i]);
                };
            };

            this.setState({
                uid: res.uid,
                isLogin: res.isLogin,
                stage: res.stage,
                endTime: res.leftTime * 1000 || false,
                list: res.list,
                topThreeData: topThreeData,
                listData: listData
            },() => console.log(this.state));                
        });
    };

    clickWatch (item, index, array) {
        if (item.uid == this.state.uid) {
            this.showToast('不可以关注自己');
            return;
        };
        if (!this.state.isLogin) {
            this.login();
        };
        this.statistics('拆礼盒-结果页->关注主播');        
        ajax({
            method: 'post',
            url: '/may_day2018/follow',
            data: {
                uid: item.uid
            },
        }).then(res => {
            if (res.code != 0) {
                this.showToast(res.msg);
                return;
            };
            let list = array;
            list[index].isFollowed = true;
            if (list.length > 3) {
                // 第4名之后的关注
                this.setState({
                    listData: list
                });
            }else{
                // 前3名的关注
                this.setState({
                    topThreeData: list
                });
            };
        });       
    };
    // 登陆
    login () {
        if (!this.state.isLogin) {
            // 未登陆
            let ua = window.navigator.userAgent.toLowerCase();
            if (/(com.meitu.myxj|com.meitu.meiyancamera)/gi.test(ua)) {
                this.showToast('需退出本页面登录美颜相机账号噢~', 1500);
                return;
            }else if(/(com.meitu.mtxx)/gi.test(ua)) {
                this.showToast('需退出本页面登录美图秀秀账号噢~', 1500);
                return;
            };
            window.location.href = `/login/web_login?login_redirect=${encodeURIComponent(location.href)}`;
            return;
        };
    };
    // toast 显示
    showToast (text) {
        this.setState({
            isShowToast: true,
            toastText: text || this.state.toastText
        });
        setTimeout(() => {
            this.setState({
                isShowToast: false
            });
        },1000);
    };
    // 跳转直播或者个人页
    redirect (type, id) {
        let ua = window.navigator.userAgent.toLowerCase();
        let uas = {
            iOS: /(iPhone|iPad|iPod|iOS)/gi.test(ua),
            Android: /android|adr/gi.test(ua),
            Mobile: /(iPhone|iPad|iPod|iOS|Android|adr|Windows Phone|SymbianOS)/gi.test(ua),
            Weibo: /(weibo)/gi.test(ua),
            WeChat: ua.match(/MicroMessenger/gi) == 'micromessenger' ? true : false,
            QQ: /qq\//gi.test(ua),
            Qzone: ua.indexOf('qzone/') !== -1,
            Meitu: /(com.meitu)/gi.test(ua),
            Meipai: /meipaimv|meipai|com.meitu.mtmv/ig.test(ua),
            Meipu: /com.meitu.meipu/ig.test(ua),
            Xiuxiu: /(com.meitu.mtxx)/gi.test(ua),
            // ios: com.meitu.myxj, android: com.meitu.meiyancamera
            Meiyan: /(com.meitu.myxj|com.meitu.meiyancamera)/gi.test(ua),
            Makeup: /com.meitu.makeup/ig.test(ua),
            Selfilecity: /com.meitu.wheecam/ig.test(ua),
            Beautyme: /com.meitu.zhi.beauty/ig.test(ua),
            Shanliao: /(com.meitu.shanliao|com.meitu.testwheetalk)/ig.test(ua),
            Twitter: /Twitter/ig.test(ua),
            Facebook: /fbav/ig.test(ua)
        };
        switch (type) {
            case 'user':
                // id为0不跳转
                if (id == 0 || !id) return;
                this.statistics('拆礼盒-结果页->榜单跳主播个人页');
                if (/meipaimv|meipai|com.meitu.mtmv/ig.test(ua)) {
                    // 美拍个人页
                    location.href = `mtmv://user?id=${id}`;
                }else if (/(com.meitu.mtxx)/gi.test(ua)) {
                    // 秀秀个人页
                    location.href = `mtmv://user?id=${id}`;
                }else {
                    // 未知个人页
                    location.href = `https://www.meipai.com/user/${id}`;
                };                
            break;
            case 'live':
                this.statistics('拆礼盒-结果页->榜单跳主播直播页');
                if (/meipaimv|meipai|com.meitu.mtmv/ig.test(ua)) {
                    // 美拍直播
                    location.href = `mtmv://live?id=${id}`;
                }else if (/(com.meitu.mtxx)/gi.test(ua)) {
                    // 秀秀直播
                    location.href = `https://www.meipai.com/live/${id}`;
                }else {
                    // 未知直播
                    location.href = `https://www.meipai.com/live/${id}`;
                };
            break;
        };
    };
    // 统计
    statistics (eventname, action = 'click', optLabel = '', optValue = '', op = '') {
        try{
            window._czc.push(['_trackEvent', eventname, action, optLabel, optValue]);
        }catch(e){

        };
    };
    // 停留时间统计
    timeSave (t) {
        if (t >= 120) {
            return;
        };
        console.log('结果页');
        this.timer = setTimeout(() => {
            this.statistics(`拆礼盒-结果页->停留大于${t}秒`);
            clearTimeout(this.timer);
            this.timeSave(t + 10);
        }, 10000);
    };
};

export default Results;